import GameControl from './GameControl';
import OnFire from './OnFire';
import { EventName } from './EventName';
import API from './API';

// 负责微信API
// 官方文档：https://developers.weixin.qq.com/minigame/dev/api/
export default class WXApi {
    private _TAG: any = "WXApi ";
    private _versions: string = "v1.0";

    // 单例模式
    private static _instance: WXApi = null;
    public static getInstance() {
        if (this._instance == null) {
            this._instance = new WXApi();
        }
        return this._instance;
    }

    videoAd: any = null;
    bannerAd: any = null;
    barTop: number = -1;
    videoStatus: any = null

    _interstitialAd = null;

    // 切换后台的时间戳
    backstageDate: any = 0

    // banner广告计数器（隐藏5次后，销毁广告重新拉取）
    bannerCount: number = 0
    bannerTotal: number = 3

    errHandle = {
        1000: '后端接口调用失败',
        1001: '参数错误',
        1002: '广告单元无效',
        1003: '内部错误',
        1004: '无合适的广告',
        1005: '广告组件审核中',
        1006: '广告组件被驳回',
        1007: '广告组件被封禁',
        1008: '广告单元已关闭',
    }

    // banner的ID
    bannerIDIndex: number = 0
    bannerIDList: any = [
        '16f0lgr3u2k16cg171',
    ]
    interstitialAdID = '';

    // 微信初始化
    init() {
        if (cc.sys.platform != cc.sys.WECHAT_GAME) return;

        printLog('微信SDK', this._TAG + this._versions);

        // 显示当前页面的转发按钮(被动拉起)
        wx.showShareMenu()
        wx.onShareAppMessage(() => {
            let info = GameControl.getInstance().getShareImgList()[0]
            return {
                title: info.desc,
                imageUrl: info.img_path,
                query: `invitationID=${GameControl.getInstance().getOpenID()}`
            }
        });

        // 获取当前手机的操作系统
        wx.getSystemInfo({
            success(res) {
                // Android/iOS
                GameControl.getInstance().setPhoneSystem(res.system);
            }
        })

        wx.onShow(function (data) {
            // printLog('小游戏回到了前台')
            // GM.OnFire.emit(Notify.AUDIO_STATUS, { key: 'bgm', status: 'resume' })

            // 判断分享是否成功
            // let closeTime = Date.now()
            // GM.OnFire.emit(Notify.SHARE_STATUS, { time: closeTime })

            // // 判断是否其他小游戏跳转回来的
            // if (GM.GameControl.getOtherGameStatus()) {
            //     printLog('是从其他小游戏回来的')
            //     GM.GameControl.setOtherGameStatus(false)

            //     // 获取到试剂（重战页面上使用到）
            //     GM.OnFire.emit(Notify.DEMO_GET_REAGENT, { key: true })
            // }
        })

        wx.onError(function (res) {
            printLog('小游戏异常', res);

        })

        wx.onHide((data) => {
            // printLog('小游戏隐藏到后台事件', data)
            // GM.OnFire.emit(Notify.AUDIO_STATUS, { key: 'stopall', status: 'stop' })

            // 提交排行榜数据
            // this.setUserCloudStorage('MAXPASS', GM.GameControl.getMaxPass())

            // 更新用户信息
            // GM.API.userUpdata().then(res => {
            //     if (res.status) {
            //         printLog('提交成功')
            //     } else {
            //         printLog('提交失败', res.data)
            //     }
            // })
        })

        // 加载视频
        // this.initVideoAd();
    }

    // 主动拉起分享界面
    // 使用格式：Constants.SdkFactory.shareAppMessage().then(res => {if (res.status) {分享成功}})
    shareAppMessage() {
        let openTime = Date.now()
        let info = GameControl.getInstance().getShareImgList()[0]
        return new Promise<any>((resolve, reject) => {
            wx.shareAppMessage({
                title: info.desc,
                imageUrl: info.img_path,
                query: `invitationID=${GameControl.getInstance().getOpenID()}`
            })

            OnFire.getInstance().once(EventName.SHARE_STATUS, (event) => {
                if (event.time) {
                    let count = event.time - openTime
                    if (count >= 3000) {
                        resolve({
                            status: true,
                            msg: '分享成功'
                        })
                    } else {
                        resolve({
                            status: false,
                            msg: '分享失败'
                        })
                    }
                } else {
                    resolve({
                        status: false,
                        msg: '分享失败'
                    })
                }
            })
        })
    }

    // 存储数据到本地
    setStorage(key: string, value: any) {
        wx.setStorageSync(key, value);
    }

    // 读取本地数据
    getStorage(key: string) {
        // let value = JSON.parse(wx.getStorageSync(key));
        // return value;
        return wx.getStorageSync(key);
    }

    // 判断本地是否存在对应的数据
    hasOwnProperty(key: string) {
        if (wx.getStorageSync(key) == "") {
            return false
        }
        return true
    }

    // 删除key值的本地缓存数据
    removeStorage(key: string) {
        wx.removeStorage({
            key: 'key',
            success(res) {
            }
        })
    }

    //  获取微信右上角按钮的坐标（按钮锚点：（0， 0.5））
    getRightMenuPos() {
        // 添加到我的小程序手势 位置调整
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            let WXScreen = wx.getSystemInfoSync();
            let wxHeight = WXScreen.screenHeight;
            let wxWidth = WXScreen.screenWidth;

            let posObject = wx.getMenuButtonBoundingClientRect();
            let menuWXPosX = posObject.left;
            let menuWXPosY = wxHeight - posObject.top - posObject.height / 2;

            let cocosHeight = cc.winSize.height;
            let cocosWidth = cc.winSize.width;

            // 世界坐标
            let worldPosX = menuWXPosX * cocosWidth / wxWidth;
            let worldPosY = menuWXPosY * cocosHeight / wxHeight;

            return new cc.Vec2(worldPosX, worldPosY);
        }
    }

    // 监听网络变化状态
    onNetworkStatusChange() {
        wx.onNetworkStatusChange((res) => {
            printLog('网络变动啦', 'onNetworkStatusChange')
            printLog('当前是否有网络连接', res.isConnected)
            printLog('网络类型', res.networkType)
        })
    }

    // 关闭网络变化状态监听
    offNetworkStatusChange() {
        wx.offNetworkStatusChange(() => {
            printLog("关闭网络变化状态监听")
        })
    }

    // 获取网络状态检测
    getNetworkType() {
        wx.getNetworkType({
            success(res) {
                return {
                    'status': 200,
                    'msg': res.networkType,
                    'client': 'wx'
                }
            },
            fail(res) {
                return {
                    'status': 503,
                    'msg': res,
                    'client': 'wx'
                }
            }
        })
    }

    // 小游戏跳转
    navigateToMiniProgram(appId, path) {
        return new Promise<any>((resolve, reject) => {
            wx.navigateToMiniProgram({
                appId: appId,
                path: path,
                success: (res) => {
                    printLog('跳转成功')

                    // 跳转成功打点
                    API.getInstance().getAllow(appId);

                    // 从导出游戏跳转到其他小游戏
                    // GameControl.getInstance().setOtherGameStatus(true)
                    resolve(true)
                },
                complete: () => {
                    cc.game.resume();
                },
                fail: (res) => {
                    printLog('跳转失败')
                    resolve(false)
                }
            });
        })
    }

    // banner广告设置位置
    // 开启广告：Constants.SdkFactory.createBannerAd();
    createBannerAd() {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            if (this.bannerAd != null) {
                this.upBarAd();
                return;
            }
            this.bannerAd = wx.createBannerAd({
                adUnitId: this.bannerIDList[this.bannerIDIndex],
                style: {
                    left: 0,
                    top: 0,
                    adIntervals: 30,
                    width: cc.winSize.width
                }
            });

            this.bannerAd.show();
            this.bannerAd.onResize(res => {
                this.upBarAd();

            });

            this.bannerAd.onError(err => {
                printLog('banner广告异常:', this.errHandle[err.errCode])
                if (err.errCode == 1004) {
                    this.bannerIDIndex == (this.bannerIDList.length - 1) ? this.bannerIDIndex = 0 : this.bannerIDIndex += 1
                    printLog('更换bannerID:', this.bannerIDList[this.bannerIDIndex])
                }
            });
        }
    }

    setBarTop(top: number) {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            this.barTop = top;
            if (this.bannerAd != null) {
                this.upBarAd();
            }
        }
    }

    // 设置广告图片大小
    upBarAd() {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            let info = wx.getSystemInfoSync();

            // 居中
            this.bannerAd.style.left = (info.screenWidth - this.bannerAd.style.realWidth) / 2;

            if (this.barTop == -1) {
                let wxh = info.screenWidth / cc.winSize.width * cc.winSize.height;
                this.bannerAd.style.top = wxh - this.bannerAd.style.realHeight;
            } else {
                this.bannerAd.style.top = info.screenWidth / cc.winSize.width * this.barTop;
            }
            this.bannerAd.show();
        }
    }

    // 隐藏广告：Constants.SdkFactory.hideBarAd();
    hideBarAd() {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            if (this.bannerAd != null) {
                this.bannerCount += 1
                if (this.bannerCount == this.bannerTotal) {
                    this.destroyBarAd()
                    return
                }
                printLog('banner广告隐藏')
                this.bannerAd.hide()
            }
        }
    }

    // 销毁广告：Constants.SdkFactory.destroyBarAd();
    destroyBarAd() {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            if (this.bannerAd != null) {
                printLog('banner广告销毁')
                this.bannerAd.destroy()
                this.bannerAd = null
                this.bannerCount = 0
            }
        }
    }

    // 初始化视频广告
    initVideoAd() {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            if (this.videoAd == null) {
                this.videoAd = wx.createRewardedVideoAd({
                    adUnitId: 'gg4qcj1loqsho14oeq'
                })

                // 视频加载完成
                this.videoAd.onLoad(() => {
                    console.log('激励视频 广告加载成功');
                })

                // 捕获视频流异常事件
                this.videoAd.onError(err => {
                    printLog('视频流异常::', this.errHandle[err.errCode])
                });

                // 捕获视频关闭事件
                this.videoAd.onClose(res => {
                    if (res && res.isEnded || res === undefined) {
                        // 正常播放结束，可以下发游戏奖励
                        // this.videoAdCallbackSuc(true);
                        console.log('正常关闭视频广告')
                        OnFire.getInstance().emit(EventName.PLAY_VIDEO_STATUS, { key: true });
                    }
                    else {
                        // 播放中途退出，不下发游戏奖励
                        // this.videoAdCallbackSuc(false);
                        console.log('还没有看完视频，关闭不正常')
                        OnFire.getInstance().emit(EventName.PLAY_VIDEO_STATUS, { key: false });
                    }
                });
            } else {
                console.log('视频组件已经加载，不需要重复加载')
            }
        }
    }

    // 视频广告播放开关
    // 使用：
    // Constants.SdkFactory.playVideoAd().then(res => {if (res.status) {播放成功}})
    playVideoAd() {
        return new Promise<any>((resolve, reject) => {
            if (this.videoAd != null) {
                this.videoAd.load().then(() => this.videoAd.show().catch(err => console.log(err)));

                // 监听视频播放状态
                OnFire.getInstance().once(EventName.PLAY_VIDEO_STATUS, res => {
                    if (res.key === true) {
                        resolve({
                            status: true,
                            msg: '播放完成'
                        });
                    } else {
                        resolve({
                            status: false,
                            msg: res
                        });
                    };
                })
            } else {
                this.initVideoAd();
            }
        })
    }

    // 微信登录
    // Constants.SdkFactory.login().then(res => {})
    login() {
        // 当发现之前的数据没有上传时，使用本地数据
        return new Promise<any>((resolve, reject) => {
            printLog('WX登录');
            wx.login({
                success: (res) => {
                    // 获取微信用户的code码，去后端获取用户数据
                    if (res.code) {
                        API.getInstance().login({ code: res.code }).then(_res => {
                            if (_res.status) {
                                this.getUserInfo(_res.data.open_id)
                                resolve({
                                    status: true,
                                    data: _res.data
                                })
                            } else {
                                resolve({
                                    status: false,
                                    data: _res.data
                                })
                            }

                        })
                    } else {
                        resolve({
                            status: true,
                            data: res.errMsg
                        })
                    }
                }
            });
        })
    }

    // 获取用户信息
    getUserInfo(open_id) {
        wx.getSetting({
            success(res) {
                if (res.authSetting['scope.userInfo']) {
                    wx.getUserInfo({
                        success: (data) => {
                            API.getInstance().saveUserInfo({
                                open_id: open_id,
                                avatar_url: data.province,
                                nickname: data.nickName
                            })
                        }
                    });
                }
            }
        });
    }

    // 上传数据到云托管，用于排行榜
    // value = {"keyname": "valuedata"} 或 value = {"keyname_1": { "keyname_1_1": "valuedata_1_1"}, "keyname_2": "value_2"}
    setUserCloudStorage(key, value) {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            wx.setUserCloudStorage({
                KVDataList: [{
                    key: key,
                    value: JSON.stringify(value)
                }],
                success: (res) => {
                    printLog('托管数据成功', res)
                },
                fail: (err) => {
                    printLog('托管数据失败', err)
                }
            })
        }
    }

    // 长震动
    vibrateLong() {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            wx.vibrateLong()
        }
    }

    // 短震动
    vibrateShort() {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            wx.vibrateShort()
        }
    }

    // 插屏
    interstitialAd(callback) {
        this._interstitialAd = wx.createInterstitialAd({
            adUnitId: this.interstitialAdID
        });

        this._interstitialAd.load().then((res) => {
            printLog('展示插屏');
            this._interstitialAd.show().catch(err => {
                printLog('插屏广告异常1:', this.errHandle[err.errCode]);
                callback(true);
            });
        }).catch(err => {
            printLog('插屏广告异常2:', this.errHandle[err.errCode]);
            callback(true);
        })

        this._interstitialAd.onLoad(() => {
            printLog('插屏广告加载完成');
        })

        this._interstitialAd.onClose(() => {
            this._interstitialAd.destroy();
            this._interstitialAd.offLoad(() => { });
            this._interstitialAd.offClose(() => { });
            this._interstitialAd.onError(() => { });
            this._interstitialAd = null;
            callback(true);
        })

        this._interstitialAd.onError((err) => {
            printLog('插屏广告异常3:', this.errHandle[err.errCode]);
            this._interstitialAd.destroy();
            this._interstitialAd.offLoad(() => { });
            this._interstitialAd.offClose(() => { });
            this._interstitialAd.onError(() => { });
            this._interstitialAd = null;
            callback(true);
        });
    }

    //开始录屏
    StartRecordScreen() {
        return;
    }

    // 停止录屏
    StopRecordScreen() {
        return;
    }

    // 分享录屏
    ShareRecordScreen() {
        return new Promise<any>((resolve, reject) => {
            resolve(true);
        });
    }
}
